package com.yungu.swift.common.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.autoconfig.redis.RedisCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.common.sensitiveword.SensitiveWordInit;
import com.yungu.swift.common.sensitiveword.SensitivewordFilter;
import com.yungu.swift.common.service.CommonSensitiveWordService;
import com.yungu.swift.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author GZL
 */
@Service
public class CommonSensitiveWordServiceImpl implements CommonSensitiveWordService {

    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private SensitiveWordInit sensitiveWordInit;

    @Override
    public ResponseData<String> getInitSensitiveWords() {
        Object sensitiveWords = redisCacheService.get("sensitiveWords");
        if (sensitiveWords != null) {
            return ResponseData.buildSuccessResponse(sensitiveWords.toString());
        }
        return ResponseData.buildSuccessResponse("");
    }

    @Override
    public ResponseData<Boolean> update(String sensitiveWords) {
        String newSensitiveWords = sensitiveWords.replaceAll(",", "\n");
        Boolean update = sensitiveWordInit.updateSensitiveWordFile(newSensitiveWords);
        if (update) {
            return ResponseData.buildSuccessResponse("敏感词库更新成功", Boolean.TRUE);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "敏感词库更新失败", Boolean.FALSE);
    }

    @Override
    public ResponseData<String> checkContainSensitiveWords(String source, int matchType) {
        if (StringUtils.isNotEmpty(source)) {
            Set<String> result = SensitivewordFilter.getSensitiveWord(source, matchType);
            if (result.isEmpty()) {
                return ResponseData.buildSuccessResponse("检查敏感词通过", "");
            }
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "检查敏感词不通过", result.toString());
        }
        return ResponseData.buildSuccessResponse("检查敏感词通过", "");
    }
}
